<template>
	<div class="mainBox">
		<!-- 下拉框查询 -->
		<el-form :inline="true" :model="ruleForm" :rules="rules"  ref="ruleForm" label-width="110px" class="formBox">
			<el-row :gutter="20">
				<el-col :span="8">
					<el-form-item label="会员姓名" prop="name">
						<el-input placeholder="会员姓名" v-model="ruleForm.name"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="联系电话" prop="phoneQuery">
						<el-input placeholder="联系电话" v-model="ruleForm.phoneQuery"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item class="secondRow_formItem">
						<el-button type="primary" icon="el-icon-search" @click="query">查询</el-button>
						<el-button type="success" @click="add">新增</el-button>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<div class="dialog">

			<el-dialog :title="title" :visible.sync="centerDialogVisible" width="80%" right>
				<el-form :inline="true" ref="add_form" :rules="addRules" :model="addForm" label-width="110px" class="formBox">
					<el-form-item label="会员姓名" prop="name">
						<el-input placeholder="请输入会员姓名" v-model="addForm.name"></el-input>
					</el-form-item>

					<el-form-item label="联系电话" prop="phone">
						<el-input placeholder="请输入联系电话" v-model="addForm.phone"></el-input>
					</el-form-item>
					<el-form-item label="登记人员" prop="registration_personnel">
						<el-input placeholder="请输入登记人员" disabled v-model="addForm.registration_personnel"></el-input>
					</el-form-item>
					<el-form-item label="家庭住址" prop="address">
						<el-input placeholder="请输入家庭住址" v-model="addForm.address"></el-input>
					</el-form-item>

					<el-form-item label="登记门店" prop="register_stores">
						<el-input placeholder="请输入登记门店" v-model="addForm.register_stores" disabled></el-input>
					</el-form-item>
					<el-form-item label="会员密码">
						<el-input placeholder="请输入会员密码" v-model="addForm.password" type="password"></el-input>
					</el-form-item>
					<el-form-item label="会员生日" prop="birthday">
						<el-date-picker value-format="yyyy-MM-dd" v-model="addForm.birthday" type="date" placeholder="选择日期" style="width: 88%;">
						</el-date-picker>
					</el-form-item>
					<el-form-item label="性别" prop="sex">
						<template>
							<el-radio v-model="addForm.sex" label="1">男</el-radio>
							<el-radio v-model="addForm.sex" label="2">女</el-radio>
						</template>
					</el-form-item>
				</el-form>
				<span slot="footer" class="dialog-footer">
					<el-button @click="centerDialogVisible = false">取 消</el-button>
					<el-button type="primary" @click="submitForm('add_form')" v-loading="addLoading">确 定</el-button>
				</span>
			</el-dialog>
		</div>

		<!-- 表格 -->
		<div class="tableBox">
			<div class="export">
				<el-button type="info" icon="el-icon-download" size="small" @click="exportExcel">导出</el-button>
			</div>
			<el-table :data="tableData" style="width:100%" stripe border id="out-table" v-loading="tableLoading">
				<el-table-column type="index" label="序号" width="80" :index="dealIndex" center></el-table-column>
				<el-table-column prop="name" label="会员姓名" center></el-table-column>
				<el-table-column prop="birthday" label="会员生日" center></el-table-column>
				<el-table-column prop="createValue" label="登记人员" center></el-table-column>

				<el-table-column prop="address" label="家庭住址" center></el-table-column>
				<el-table-column prop="phone" label="联系电话" center></el-table-column>
				<el-table-column prop="sex" label="性别" center>
           <template slot-scope="scope">
            <span v-if="scope.row.sex=='1'">男</span>
            <span v-if="scope.row.sex=='2'">女</span>           
        </template>
        </el-table-column>
				<el-table-column prop="storeValue" label="登记门店" center>

				</el-table-column>
				<el-table-column label="操作">
					<template slot-scope="scope">
						<el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
						<el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination style="padding:20px 0;text-align:center;" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="current" :page-sizes="[2, 5, 10, 20, 50]" :page-size="size" layout="total,sizes,prev,pager,next,jumper" :total="total">
			</el-pagination>
		</div>
	</div>
</template>
<script>
import {
  memberList,
  memberAdd,
  memberDel,
  memberUpdate,
  storeList
} from "@/api/user";
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  data() {
    var checkPhone = (rule, value, callback) => {
      if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error("手机格式有误"));
      } else if (!value) {
        callback(new Error("手机号不能为空！"));
      } else {
        callback();
      }
    };
    return {
      up_data: "",
      tableLoading: true,
      current: 1,
      size: 10,
      title:"",
      total: 0,
      userId: "",
      addLoading: false,
      ruleForm: {
        name: "",
        phoneQuery: ""
      },

      addForm: {
        name: "",
        birthday: "",
        phone: "",
        password: "",
        registration_personnel: "",
        address: "",
        sex: "",
        register_stores: ""
      },
      rules:{
        phoneQuery:[{validator: checkPhone, trigger: 'blur'}],
      },
      addRules: {
        name: [
          {
            required: true,
            message: "请输入会员名字",
            trigger: "blur"
          }
        ],
        phone: [
         
            { validator: checkPhone, trigger: 'blur' }
        ],

        register_stores: [
          {
            required: true,
            message: "请输入登记门店",
            trigger: "blur"
          }
        ],
        registration_personnel: [
          {
            required: true,
            message: "请输入登记人员",
            trigger: "blur"
          }
        ]
      },
      centerDialogVisible: false,
      form: {
        region: ""
      },
      tableData: [],
      currentPage1: 10,
      currentPage2: 10,
      currentPage3: 3
    };
  },

  mounted() {
    this.memberListGet();
  },
  methods: {
    //会员列表
    memberListGet() {
      memberList({ current: this.current, size: this.size }).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.records;
          this.total = res.data.total;
          this.tableLoading = false;
        } else {
          this.$message.error("会员列表获取失败");
          this.tableLoading = false;
        }
      });
    },
    query() {

      var data = {};
      if (this.ruleForm.name == "") {
        data = {
          current: this.current,
          size: this.size,
          phone: this.ruleForm.phoneQuery
        };
      }
      if (this.ruleForm.phoneQuery == "") {

        data = {
          current: this.current,
          size: this.size,
          name: this.ruleForm.name
        };
	  }
	    if (this.ruleForm.phoneQuery == "" && this.ruleForm.name == "") {
		
        data = {
          current: this.current,
          size: this.size,

        };
      }
      if (this.ruleForm.phoneQuery !== "" && this.ruleForm.name !== "") {
        data = {
          current: this.current,
          size: this.size,
          name: this.ruleForm.name,
          phone: this.ruleForm.phoneQuery
        };
      }
      memberList(data).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.records;
          this.total = res.data.total;
          this.tableLoading = false;
        } else {
          this.$message.error("会员列表获取失败");
          this.tableLoading = false;
        }
      });
    },

    //会员删除
    handleDelete(row) {
      let that = this;
      this.$confirm("是否删除该会员, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          memberDel({ id: row.id }).then(res => {
            if (res.code == 200) {
              that.$message.success("删除成功");
              this.memberListGet()
            } else {
              that.$message.error("删除失败");

            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    exportExcel() {
      /* 从表生成工作簿对象 */
      var wb = XLSX.utils.table_to_book(document.querySelector("#out-table"));
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          //Blob 对象表示一个不可变、原始数据的类文件对象。
          //Blob 表示的不一定是JavaScript原生格式的数据。
          //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
          //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: "application/octet-stream" }),
          //设置导出文件名称
          "sheetjs.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },

    //修改会员弹框
    handleEdit(row) {
      this.up_data = 1;
       this.title="修改会员"
      this.centerDialogVisible = true;
      this.userId = row.id;
      this.addForm.registration_personnel = JSON.parse(
        this.$store.state.user.getUser
      ).holder;
      this.addForm.phone = row.phone;
      this.addForm.name = row.name;
      this.addForm.birthday = row.birthday;
      this.addForm.address = row.address;
      this.addForm.sex = row.sex;
      this.addForm.password = row.password;
      this.addForm.registration_personnel = row.createValue;
      this.addForm.register_stores = row.storeValue;
    },
    //添加会员弹框
    add() {
      this.centerDialogVisible = true;
      this.title="新增会员"
      this.up_data = 0;
      this.addForm.phone = "";
      this.addForm.name = "";
      this.addForm.birthday = "";
      this.addForm.address = "";
      this.addForm.sex = "";
      this.addForm.password = "";
      // createValue:this.addForm.registration_personnel,
      this.addForm.register_stores = JSON.parse(
        this.$store.state.user.getStore
      ).storeName;
      this.addForm.registration_personnel = JSON.parse(
        this.$store.state.user.getUser
      ).holder;
    },
    //添加会员

    submitForm(formName) {
      this.addLoading = true;
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.up_data == 0) {
            let data = {
              phone: this.addForm.phone,
              name: this.addForm.name,
              birthday: this.addForm.birthday,
              address: this.addForm.address,
              sex: this.addForm.sex,
              password: this.addForm.password
            };
            if (this.addForm.password == "") {
      
              this.$message.error("会员密码不能为空");
               this.addLoading = false;
              return false;
            }
            memberAdd(data).then(res => {
              if (res.code == 200) {
                this.$message.success("增加成功");
                this.addLoading = false;
                this.memberListGet();
                this.centerDialogVisible = false;
              } else {
                this.$message.success(res.msg);
                this.addLoading = false;
              }
            });
          } else {
            let data = {
              phone: this.addForm.phone,
              name: this.addForm.name,
              birthday: this.addForm.birthday,
              address: this.addForm.address,
              sex: this.addForm.sex,
              password: this.addForm.password,
              id: this.userId
            };
            memberUpdate(data).then(res => {
              if (res.code == 200) {
                this.$message.success("修改成功");
                this.addLoading = false;

                this.memberListGet();
                this.centerDialogVisible = false;
              } else {
                this.$message.success("修改失败");
                this.addLoading = false;
              }
            });
          }
        } else {
          this.addLoading = false;
          return false;
        }
      });
    },
    handleCurrentChange(val) {
      this.current = val;
      this.memberListGet();
    },
    handleSizeChange(val) {
      this.size = val;
      this.memberListGet();
    },
    // 处理table连续序号
    dealIndex(index) {
      var self = this;
      return index + 1 + (self.current - 1) * self.size;
    }
  }
};
</script>

<style lang="scss" scoped>
.formBox {
  margin-top: 20px;
}

.tableBox {
  margin: 58px 20px 0 20px;
  .export {
    text-align: right;
    margin-bottom: 30px;
  }
}

.el-button--mini,
.el-button--mini.is-round {
  padding: 3px 10px;
}
</style>
